#include "XMLParser.h"

#include <msxml6.h>

#include "ICallDispatcher.h"

#include "ParseHandler.h"
#include "ParsingErrorHandler.h"

namespace XMLSAX
{
	namespace Core
	{
		XMLParser::XMLParser()
		{
			HRESULT hr = CoCreateInstance(__uuidof(SAXXMLReader60), NULL, CLSCTX_ALL, __uuidof(ISAXXMLReader), (void **)&pReader);

			if(SUCCEEDED(hr))
			{
				pHandler = new ParseHandler();
				pErrorHandler = new ParsingErrorHandler();

				hr = pReader->putContentHandler((ISAXContentHandler *)pHandler);

				if(SUCCEEDED(hr))
				{
					hr = pReader->putErrorHandler((ISAXErrorHandler *)pErrorHandler);
				}
			}
		}

		XMLParser::~XMLParser()
		{
			pReader->putContentHandler(NULL);
			pReader->putErrorHandler(NULL);

			delete pErrorHandler;
			delete pHandler;

			if(pReader != NULL)
			{
				pReader->Release();
				pReader = NULL;
			}
		}

		void XMLParser::ParseDocument( const std::wstring& fileName )
		{
			if(pReader != NULL)
			{
				pReader->parseURL(fileName.data());
			}
		}

		void XMLParser::SetCallDispatcher(XMLSAX::Common::ICallDispatcher *dispatcher )
		{
			pDispatcher = dispatcher;

			if(pHandler != NULL)
			{
				pHandler->SetCallDispatcher(pDispatcher);
			}
		}
	}
}